
import { trimAll } from './string'

// 解决滚动穿透问题

export function fixedBody() {
  let scrollTop = document.body.scrollTop || document.documentElement.scrollTop
  document.body.style.cssText += 'position:fixed;width:100%;top:-' + scrollTop + 'px;'
}

export function looseBody() {
  let body = document.body;
  body.style.position = '';
  let top = body.style.top;
  document.body.scrollTop = document.documentElement.scrollTop = -parseInt(top);
  body.style.top = '';
}


//从JSON转成string: a=1&b=3
export function parseJsonToString(qObj) {
  var qArr = [];
  if (qObj) {
    for (var i in qObj) {
      qArr.push(i + '=' + qObj[i]);
    }
  }
  return qArr.join('&');
}

/**
 * 对象或者数组对象的深度拷贝 通用
 * @param {*} obj
 */
export function deepCopy(obj) {
  let result = null;
  if (typeof obj == "object") {
    //复杂数据类型
    result = obj.constructor == Array ? [] : {};
    for (let i in obj) {
      result[i] = typeof obj[i] == "object" ? deepCopy(obj[i]) : obj[i];
    }
  } else {
    //简单数据类型 直接 == 赋值
    result = obj;
  }
  return result;
}

export function simDeepCopy(obj) {
  if (!obj) {
    return obj;
  }
  return JSON.parse(JSON.stringify(obj));
}


export function getBase64(file) {
  return new Promise(function(resolve, reject) {
    let reader = new FileReader();
    let imgResult = "";
    reader.readAsDataURL(file);
    reader.onload = function() {
      imgResult = reader.result;
    };
    reader.onerror = function(error) {
      reject(error);
    };
    reader.onloadend = function() {
      resolve(imgResult);
    };
  });
}


export function getBase64_sub(file) {
  return new Promise(function(resolve, reject) {
    let reader = new FileReader();
    let imgResult = "";
    reader.readAsDataURL(file);
    reader.onload = function() {
      imgResult = reader.result;
    };
    reader.onerror = function(error) {
      reject(error);
    };
    reader.onloadend = function() {
      imgResult = imgResult.substr(imgResult.indexOf(';base64,') + 8, imgResult.length);
      resolve(imgResult);
    };
  });
}


/*传入身份证号码，将身份证号码中的生日解析出来*/
export function getBirthdayFromIdCard(idCard) {
  var birthday = "";
  if (idCard != null && idCard != "") {
    if (idCard.length == 15) {
      birthday = "19" + idCard.substr(6, 6);
    } else if (idCard.length == 18) {
      birthday = idCard.substr(6, 8);
    }
    birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
  }
  return birthday;
}


/*传入出生日期，获得年龄*/
export function jsGetAge(strBirthday) {
  var returnAge;
  var strBirthdayArr = strBirthday.split("-");
  var birthYear = strBirthdayArr[0];
  var birthMonth = strBirthdayArr[1];
  var birthDay = strBirthdayArr[2];
  var d = new Date();
  var nowYear = d.getFullYear();
  var nowMonth = d.getMonth() + 1;
  var nowDay = d.getDate();
  if (nowYear == birthYear) {
    returnAge = 0;//同年 则为0岁
  } else {
    var ageDiff = nowYear - birthYear; //年之差
    if (ageDiff > 0) {
      if (nowMonth == birthMonth) {
        var dayDiff = nowDay - birthDay;//日之差
        if (dayDiff < 0) {
          returnAge = ageDiff - 1;
        } else {
          returnAge = ageDiff;
        }
      } else {
        var monthDiff = nowMonth - birthMonth;//月之差
        if (monthDiff < 0) {
          returnAge = ageDiff - 1;
        } else {
          returnAge = ageDiff;
        }
      }
    } else {
      returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天
    }
  }
  return returnAge;//返回周岁年龄
}


/** 验证15位数身份证号码中的生日是否是有效生日  
  * @param idCard15 15位书身份证字符串  
  * @return  
  */
export function isValidityBrithBy15IdCard(idCard15) {
  var year = idCard15.substring(6, 8);
  var month = idCard15.substring(8, 10);
  var day = idCard15.substring(10, 12);
  var temp_date = new Date(year, parseFloat(month) - 1, parseFloat(day));
  // 对于老身份证中的你年龄则不需考虑千年虫问题而使用getYear()方法   
  if (temp_date.getYear() != parseFloat(year)
    || temp_date.getMonth() != parseFloat(month) - 1
    || temp_date.getDate() != parseFloat(day)) {
      return false;
  } else {
    return true;
  }
};

/**校验身份证号码是否正确*/
export function idCardValidate(idCard) {
  if (typeof (idCard) != 'string') {
    return false;
  }
  idCard = trimAll(idCard);
  if (idCard.length == 15) {
    return isValidityBrithBy15IdCard(idCard);
  } else if (idCard.length == 18) {
    var a_idCard = idCard.split("");
    if (isValidityBrithBy18IdCard(idCard) && isTrueValidateCodeBy18IdCard(a_idCard)) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
};

/** 验证18位数身份证号码中的生日是否是有效生日  
  * @param idCard 18位书身份证字符串  
  * @return  
  */
export function isValidityBrithBy18IdCard(idCard18) {
  var year = idCard18.substring(6, 10);
  var month = idCard18.substring(10, 12);
  var day = idCard18.substring(12, 14);
  var temp_date = new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
  // 这里用getFullYear()获取年份，避免千年虫问题   
  if (temp_date.getHours() != 0) { // 1989-04-16 转换会变成1989-04-15 23:00:00导致判断不通过，所以不是0小时则跳过后面的校验
    return true;
  }
  if (temp_date.getFullYear() != parseInt(year)
    || temp_date.getMonth() != parseInt(month) - 1
    || temp_date.getDate() != parseInt(day)) {
      return false;
  } else {
    return true;
  }
};



/** 判断身份证号码为18位时最后的验证位是否正确  
 * @param a_idCard 身份证号码数组  
 * @return  
 */
export function isTrueValidateCodeBy18IdCard(a_idCard) {
  var ValideCode = [1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2];// 身份证验证位值.10代表X
  var Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1];// 加权因子

  if (a_idCard.length != 18) return false;
  var sum = 0;                             // 声明加权求和变量   
  if (a_idCard[17].toLowerCase() == 'x') {
    a_idCard[17] = 10;                    // 将最后位为x的验证码替换为10方便后续操作   
  }
  for (var i = 0; i < 17; i++) {
    sum += Wi[i] * a_idCard[i];            // 加权求和   
  }
  var valCodePosition = sum % 11;                // 得到验证码所位置   
  if (a_idCard[17] == ValideCode[valCodePosition]) {
    return true;
  } else {
    return false;
  }
};



/*
 * 判断object是否为空
 * @param a
 * @returns {boolean} true为非空，false为空
 */
export function isNotEmptyObject(obj) {
  let j = false;
  obj = typeof obj == 'object' ? obj : JSON.parse(obj);
  for (let item in obj) {
    return !j
  }
  return j;
}

//判断是否为整数
export function isInteger(str) {
  return /^\d+$/.test(str) || /^-\d+$/.test(str);
}

/**
 * 设置，添加，删除本地存储
 *obj {name:'id',value:id};
 key:则存储字段名称；
 */
export function setStorage(obj) {
  window.localStorage.setItem(obj.name, obj.value)
}

export function getStorage(key) {
  return localStorage.getItem(key);
}

export function deleteStorage(key) {
  window.localStorage.removeItem(key);
}

/*清除所有本地信息*/
export function storageClear() {
  window.localStorage.clear();
}

/*cookie*/
export function setcookie(name, value, hours) {
  // let Days = 30;
  let exp = new Date();
  exp.setTime(exp.getTime() + (hours * 60 * 60 * 1000));
  document.cookie = name + "=" + decodeURI(value) + ";expires=" + exp.toGMTString();
}

export function deletcookie(name, value) {
  this.setcookie(name, "", -1)
}

export function getcookie(name) {
  let arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
  if (arr != null) {
    return (arr[2]);
  } else {
    return "";
  }
}







export function getQueryString(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  var r = window.location.search.substr(1).match(reg);

  if (r != null) {
    return unescape(r[2]);
  }
  return null;
}


/**
 * 是否为pc端
 */
export function isPc() {
  let userAgentInfo = navigator.userAgent.toLowerCase();
  let Agents = new Array("android", "iphone", "symbianOS", "windows phone", "ipad", "ipod");
  let flag = true;
  for (let v = 0; v < Agents.length; v++) {
    if (userAgentInfo.indexOf(Agents[v]) > 0) {
      flag = false;
      break;
    }
  }
  return flag;
}



// axios
// .post(url, forms, {
//   headers: {
//     "content-type": "multipart/form-data",
//     token: this.token,
//   },
// })
// .then((res) => {
//   //如果传入的响应状态码为200，则成功将文件发送给后台
//   if (res.data.status === 200) {
//     console.log(res);
//     //this.imageData = res.data.showapi_res_body;
//     //this.isShow = false;
//     //this.showList = true;
//     //Toast(res.data.showapi_res_body.remark);
//   } else {
//     //Toast(res.data.msg);
//     //this.isShow = false;
//     console.log(res.data.msg)//这块是请求失败后台给返回的相应的数据
//   }
// });

export function uploadPicture(url, file, pictureType, callback) {
  let xhr = new XMLHttpRequest();
  let fd = new FormData();
  fd.append("file", file);
  fd.append("pictureType", pictureType);
  fd.append("token", '');
  xhr.open("POST", url, true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      // Handle response.
      if (xhr.status == 200) {
        const data = JSON.parse(xhr.responseText);
        //返回的url中参数Signature如果含有'+'会导致图片无法访问，根本原因是后端sdk导致，暂时由前端来处理下
        if (data && data.data && data.data.url) {
          const url = data.data.url;
          let urlArr = url.split('Signature=');
          let signature = urlArr[1];
          data.data.url = signature ? `${urlArr[0]}Signature=${encodeURIComponent(decodeURIComponent(signature))}` : urlArr[0];
        }
        callback(data);
      } else {
        console.log(xhr.responseText); // handle response.
      }
    }
  };
  xhr.send(fd);
}


import CryptoJS from 'crypto-js'
/**
 * 加密（需要先加载lib/aes/aes.min.js文件）
 * word 必须是字符串
 */
export function encrypt(word, key) {

  if (!key) {
    return '';
  } else {
    key = CryptoJS.enc.Utf8.parse(key);
  }
  var srcs = CryptoJS.enc.Utf8.parse(word);
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.toString();
}
/**
 * 解密
 */
export function decrypt(word, key) {
  try {
    if (!key) {
      return '';
    } else {
      key = CryptoJS.enc.Utf8.parse(key);
    }
    var decrypt = CryptoJS.AES.decrypt(word, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    });
    return CryptoJS.enc.Utf8.stringify(decrypt).toString();
  } catch (e) {
    return '';
  }
}


export function makeSign(appid, nonce, timestamp) {
  var authStr = 'appid=' + appid + '&nonce=' + nonce + '&timestamp=' + timestamp + '&appSecret=' + process.env.VUE_APP_MY;
  let str = CryptoJS.algo.MD5.create().update(authStr).finalize().toString(CryptoJS.enc.Hex).toUpperCase();
  return str;
}


export function isPhone() {
  var u = navigator.userAgent;
  var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
  var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

  let isWxwork = /wxwork/i.test(navigator.userAgent.toLowerCase());
  if (isAndroid || isiOS || isWxwork) {
    return true;
  } else {
    return false;
  }
}


/** 检查手机号码的合法性
 * @param {*} phoneNum 
 */
export function checkPhoneNum(phoneNum) {
  let reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
  return reg.test(phoneNum);
}


/**
 * 通过身份证判断性别
 * @param {身份证号码} idCard
 */
export function getSex(idCard) {
  var sexStr = "";
  if (idCard.length == 15 || idCard.length == 18) {
    if (parseInt(idCard.slice(-2, -1)) % 2 == 1) {
      sexStr = "1";
    } else {
      sexStr = "2";
    }
  }
  return sexStr;
};



//手机号码脱敏
export function phoneMask(str) {
  return str.replace(/(\d{3})\d*(\d{4})/, "$1****$2"); // 130****56
}

//身份证脱敏
export function sfzhMask(str) {
  return str.replace(/^(.{4})(?:\w+)(.{4})$/, "$1****$2"); // 5123****5645
}

export function textMask(str) {
  return str.replace(/(\d{3})\d*(\d{4})/, "$1****$2"); // 130****56
}



import router from '@/modules/CST/router/index'
//主要用于侧栏显示
export function initRouter(userInfo) {
  let routerList = router.options.routes;
  let main_list = [];
  let return_list = [];
  let YMQX = userInfo.YMQX;
  let ROLE_ID = userInfo.ROLE_ID;

  for (let v = 0; v <= routerList.length - 1; v++) {
    let item = routerList[v];
    if (item.name == 'mainHtml') {
      main_list = item.children;
      break;
    }
  }
  if (ROLE_ID.includes("1") || ROLE_ID.includes(1)) { //管理员全部返回
    // console.log(main_list)
    return main_list
  } else {
    main_list.forEach((item) => {
      if (YMQX.includes(item.meta.ID) || item.meta.ID == "0") {
        return_list.push(item);
      }
    })
    return return_list;
  }
}


function findObjectsWithId(arr, result = []) {
  for (const item of arr) {
    if (item.meta.hasOwnProperty('ID') && item.meta.ID != '0') {
      result.push(item.meta);
    }
    if(item.children) {
      findObjectsWithId(item.children, result);
    }
  }
  return result;
}

export function getAllRouterId() {
  let routerList = (router.options.routes);
  return findObjectsWithId(routerList);
}
